package com.cloudknow.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;


import com.cloudknow.Base.BasePresenter;
import com.cloudknow.Base.BaseView;
import com.cloudknow.dialogs.CustomProgressDialog;
import com.cloudknow.utils.NetUtil;
import com.cloudknow.utils.TUtil;
import com.cloudknow.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

/**
 * 创建日期：2019/1/7 on 14:54
 * 描述:
 * 作者:ShuY HM11
 */
public abstract class BaseFragment extends Fragment {
    private static final String TAG = BaseFragment.class.getSimpleName();

    protected Context context;
    protected Activity activity;
    protected View rootView;

    private boolean isFirstVisible;
    private boolean isFragmentVisible;

    protected int pageIndex = 1; // 当前页码
    protected int pageSize = 10; // 每次加载页码


    private CustomProgressDialog pd;

    protected enum STATE {REFRESH, LOADMORE}





    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //参数初始化
        context = getActivity();
        activity = getActivity();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(getLayoutResource(), container, false);
        }
        ButterKnife.bind(this, rootView);
        initializeAdvance();
        return rootView;
    }

    /**
     * 加载layout
     *
     * @return
     */
    protected abstract int getLayoutResource();

    @Override
    public void onDestroy() {
        super.onDestroy();

        initVariable();

    }

    protected void initializeAdvance() {
        //所以条件是view初始化完成并且对用户可见
        receiveData();
        initializeNavigation();
        initializeView();
        if (NetUtil.isNetworkAvailable(activity)) {
            loadDataFromServer();
        } else {
            ToastUtils.showToast(context, "亲~无网络啦,请检查你的网络配置哦");
        }
    }

    //setUserVisibleHint()在Fragment创建时会先被调用一次，传入isVisibleToUser = false
    //如果当前Fragment可见，那么setUserVisibleHint()会再次被调用一次，传入isVisibleToUser = true
    //如果Fragment从可见->不可见，那么setUserVisibleHint()也会被调用，传入isVisibleToUser = false
    //总结：setUserVisibleHint()除了Fragment的可见状态发生变化时会被回调外，在new Fragment()时也会被回调
    //如果我们需要在 Fragment 可见与不可见时干点事，用这个的话就会有多余的回调了，那么就需要重新封装一个

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        //setUserVisibleHint()有可能在fragment的生命周期外被调用
        if (null == rootView) {
            return;
        }

        if (isFirstVisible && isVisibleToUser) {
            initializeAdvance();
            isFirstVisible = false;
        }

        if (isVisibleToUser) {
            isFragmentVisible = true;
            return;
        }

        if (isFragmentVisible) {
            isFragmentVisible = false;
        }
    }



    private void initVariable() {
        isFirstVisible = true;
        isFragmentVisible = false;
        rootView = null;
    }

    /**
     * 接受数据
     */
    protected abstract void receiveData();

    /**
     * 导航栏初始化
     */
    protected abstract void initializeNavigation();

    /**
     * 视图初始化
     */
    protected abstract void initializeView();

    /**
     * 调用接口
     */
    protected abstract void loadDataFromServer();

    /**
     * 跳转activity
     */
    public void openActivity(Class<?> pClass) {
        openActivity(pClass, null);
    }

    /**
     * 跳转activity
     */
    public void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        context.startActivity(intent);
    }

    /**
     * 显示dialog
     */
    public void showProgressDialog() {

        try {
            if (null == pd) {
                pd = new CustomProgressDialog();
            }
            if (!pd.isAdded() && !pd.isVisible() && !pd.isRemoving()) {

                FragmentTransaction ft = getFragmentManager().beginTransaction();

                /*
                 * 如果不执行remove()，对话框即不会进入onDismiss()状态。会被显示在新的对话框下方，是可见的。
                 * 主要考虑美观的问题，如果下面的对话框大于上面的对话框就很难看了。 对于Dialog，container为0或者null。
                 */
//                ft.remove();
                /*
                 * 将当前的PromptDialogFragment加入到回退堆栈，当用户按返回键，或者通过按帮助框的Close按钮dismiss帮助框是，
                 * 重新显示提示框。 对于back stack的处理，系统具有一定的智能。例如：执行两次addToStackStack()，实际不会重复压栈。
                 * 有例如：注释掉remove()语句，即提示框不消失，而是在帮助框的下面。
                 * 但是在实验中发现是否有addToBackStack()都不会结果有影响，系统能够分析到对象存在，不需要压栈。没有去查源代码，
                 * 猜测通过mBackStackId比对来进行智能处理。
                 */
                ft.addToBackStack(null);
                ft.commitAllowingStateLoss();
                pd.show(getFragmentManager(), "CustomProgressDialog");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消dialog
     */
    public void hideProgressDialog() {
        if (null != pd) {
            pd.dismiss();
        }
    }

    /**
     * 以下都是和申请权限有关
     */
    private int REQUEST_CODE_PERMISSION = 0x00099;

    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    public void requestPermission4Base(String[] permissions, int requestCode) {
        this.REQUEST_CODE_PERMISSION = requestCode;
        if (checkPermissions(permissions)) {
            permissionSuccess(REQUEST_CODE_PERMISSION);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(getActivity(),
                    needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
        }
    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    private boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) !=
                    PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }

    /**
     * 系统请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(REQUEST_CODE_PERMISSION);
            } else {
                permissionFail(REQUEST_CODE_PERMISSION);
                showTipsDialog();
            }
        }
    }

    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(getActivity())
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setCancelable(false)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }


    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
        startActivity(intent);
    }

    /**
     * 获取权限成功
     *
     * @param requestCode
     */
    public void permissionSuccess(int requestCode) {
        Log.d(TAG, "获取权限成功=" + requestCode);
    }

    /**
     * 权限获取失败
     *
     * @param requestCode
     */
    public void permissionFail(int requestCode) {
        Log.d(TAG, "获取权限失败=" + requestCode);
    }

    /**
     * 以上都是和申请权限有关
     */
}
